package com.dwxt.sport.business.service;

import com.alibaba.fastjson.JSON;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import com.dwxt.sport.business.dao.OutdoorFitnessEquipmentMapper;
import com.dwxt.sport.business.dao.OutdoorFitnessMapper;
import com.dwxt.sport.business.entity.OutdoorFitness;
import com.dwxt.sport.business.entity.OutdoorFitnessEquipment;
import com.dwxt.sport.business.vo.outdoorFitness.InsertOrUpdateOutdoorFitnessEquipmentVo;
import com.dwxt.sport.business.vo.outdoorFitness.InsertOrUpdateOutdoorFitnessVo;
import com.dwxt.sport.business.vo.outdoorFitness.SelectOutdoorFitnessVo;
import com.dwxt.sport.constant.CommonConstant;
import com.dwxt.sport.exception.CustomException;
import com.dwxt.sport.util.BusinessValidationUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 室外健身器材 相关 Service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-07-27 16:05
 */
@Service
public class OutdoorFitnessService {

    @Resource
    OutdoorFitnessMapper outdoorFitnessMapper;

    @Resource
    OutdoorFitnessEquipmentMapper equipmentMapper;

    /**
     * @方法名：insertOutdoorFitness
     * @描述： 新增室外健身器材
     * @作者： kjz
     * @日期： Created in 2020/7/27 16:34
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOutdoorFitness(InsertOrUpdateOutdoorFitnessVo insertVo) {
        OutdoorFitness outdoorFitness = new OutdoorFitness()
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                .setStreetId(insertVo.getStreetId()) //街道id
                .setName(insertVo.getName()) //设备名称
                .setEquipmentsImgUrl(insertVo.getEquipmentsImgUrl()) //设备图片地址
                .setUnitType(insertVo.getDeviceType()) //设备类型
                .setRecommendedCoverage(insertVo.getRecommendedCoverage()); //建议覆盖率

       return outdoorFitnessMapper.insert(outdoorFitness);
    }

    /**
     * @方法名：updateOutdoorFitness
     * @描述： 更新室外健身器材
     * @作者： kjz
     * @日期： Created in 2020/7/27 16:53
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateOutdoorFitness(InsertOrUpdateOutdoorFitnessVo updateVo) {
        String id = updateVo.getId();
        if(!BusinessValidationUtil.verifyId(id)){
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        OutdoorFitness outdoorFitness = new OutdoorFitness()
                .setId(id).setUpdateTime(LocalDateTime.now())
                .setStreetId(null) //街道id
                .setName(updateVo.getName()) //设备名称
                .setEquipmentsImgUrl(updateVo.getEquipmentsImgUrl()) //设备图片地址
                .setUnitType(updateVo.getDeviceType()) //设备类型
                .setRecommendedCoverage(updateVo.getRecommendedCoverage()); //建议覆盖率

        return outdoorFitnessMapper.updateByPrimaryKeySelective(outdoorFitness);
    }

    /**
     * @方法名：getOutdoorFitnessByPage
     * @描述： 按条件查询室外健身器材列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/27 17:12
     */
    public PageInfo<OutdoorFitness> getOutdoorFitnessByPage(SelectOutdoorFitnessVo selectVo) {
        PageHelper.startPage(selectVo.getPageNum(), selectVo.getPageSize());
        System.err.println(JSON.toJSON(selectVo));
        List<OutdoorFitness> list = outdoorFitnessMapper.getOutdoorFitnessByPage(selectVo);
        list.forEach(outdoorFitness -> {
            outdoorFitness.setEquipmentsImgUrl(CommonConstant.FILE_SERVER+outdoorFitness.getEquipmentsImgUrl());
        });
        PageInfo<OutdoorFitness> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：deleteOutdoorFitnessByIds
     * @描述： 根据ids批量删除室外健身器材
     * @作者： kjz
     * @日期： Created in 2020/7/27 17:41
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteOutdoorFitnessByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        return this.outdoorFitnessMapper.deleteOutdoorFitnessByIds(idArray);
    }

    /******************************************************************  关联设备  ******************************************************************************/
    /**
     * @方法名：getOutdoorFitnessEquipmentByPage
     * @描述： 根据室外健身器材的id查询关联设备的列表(带分页)
     * @作者： kjz
     * @日期： Created in 2020/7/27 18:24
     */
    public PageInfo<OutdoorFitnessEquipment> getOutdoorFitnessEquipmentByPage(Integer pageNum, Integer pageSize, String outdoorFitnessId) {
        PageHelper.startPage(pageNum==null?1:pageNum, pageSize==null?10:pageSize);
        List<OutdoorFitnessEquipment> list = equipmentMapper.selectEquipmentByOutdoorFitnessId(outdoorFitnessId);
        PageInfo<OutdoorFitnessEquipment> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * @方法名：insertOutdoorFitnessEquipment
     * @描述： 新增室外健身器材关联的设备
     * @作者： kjz
     * @日期： Created in 2020/7/28 10:41
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOutdoorFitnessEquipment(InsertOrUpdateOutdoorFitnessEquipmentVo insertVo) {

        String outdoorFitnessId = insertVo.getOutdoorFitnessId();

        OutdoorFitnessEquipment outdoorFitnessEquipment = new OutdoorFitnessEquipment()
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                .setOutdoorFitnessId(outdoorFitnessId) //室外健身器材关联id
                .setEquipmentId(insertVo.getEquipmentId()) //设备id
                .setDeviceLocation(insertVo.getDeviceLocation()) //设备位置(暂时不确定是选择还是输入)
                .setSession(insertVo.getSession()) //使用频率(次/天)
                .setBuildingUse(insertVo.getBuildingUse()) //使用人次
                .setAvg(insertVo.getAverageUsageTime()) //平均使用时长
                .setTotalUsageTime(insertVo.getTotalUsageTime()) //使用总时长
                .setDeviceStates(insertVo.getDeviceStates()); //设备状态

        int result = equipmentMapper.insert(outdoorFitnessEquipment);

        if(result>0){
            this.updateOutdoorFitnessById(outdoorFitnessId);
        }
       return result;
    }

    /**
     * @方法名：updateOutdoorFitnessEquipment
     * @描述： 更新室外健身器材关联的设备
     * @作者： kjz
     * @日期： Created in 2020/7/28 14:25
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateOutdoorFitnessEquipment(InsertOrUpdateOutdoorFitnessEquipmentVo updateVo) {
        String id = updateVo.getId();
        if(!BusinessValidationUtil.verifyId(id)){
            throw new CustomException(StatusCode.ID_IS_NULL);
        }

        OutdoorFitnessEquipment outdoorFitnessEquipment = new OutdoorFitnessEquipment()
                .setUpdateTime(LocalDateTime.now())
                .setOutdoorFitnessId(null) //室外健身器材关联id
                .setEquipmentId(updateVo.getEquipmentId()) //设备id
                .setDeviceLocation(updateVo.getDeviceLocation()) //设备位置(暂时不确定是选择还是输入)
                .setSession(updateVo.getSession()) //使用频率(次/天)
                .setBuildingUse(updateVo.getBuildingUse()) //使用人次
                .setAvg(updateVo.getAverageUsageTime()) //平均使用时长
                .setTotalUsageTime(updateVo.getTotalUsageTime()) //使用总时长
                .setDeviceStates(updateVo.getDeviceStates()); //设备状态
        int result = equipmentMapper.updateByPrimaryKeySelective(outdoorFitnessEquipment);

        if(result>0){
            String outdoorFitnessId = equipmentMapper.selectByPrimaryKey(id).getOutdoorFitnessId();
            this.updateOutdoorFitnessById(outdoorFitnessId);
        }

        return result;
    }

    /**
     * @方法名：updateOutdoorFitnessById
     * @描述： 新增或更新关联设备成功后更新室外运动器材需要计算的数据
     * @作者： kjz
     * @日期： Created in 2020/8/4 17:01
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateOutdoorFitnessById(String outdoorFitnessId) {
        HashMap map = equipmentMapper.selectStatisticsByHealthId(outdoorFitnessId);
        OutdoorFitness outdoorFitness = new OutdoorFitness()
                .setAmount(Integer.valueOf(map.get("amount").toString()))
                .setSportsPeople(Integer.valueOf(map.get("sportsPeople").toString()))
                .setAvg(Double.parseDouble(map.get("avgSportsTime").toString()))
                .setUpdateTime(LocalDateTime.now())
                .setId(outdoorFitnessId);
        return outdoorFitnessMapper.updateByPrimaryKeySelective(outdoorFitness);
    }

    /**
     * @方法名：deleteOutdoorFitnessEquipmentByIds
     * @描述： 根据ids批量删除室外健身器材关联的设备
     * @作者： kjz
     * @日期： Created in 2020/7/29 11:06
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteOutdoorFitnessEquipmentByIds(String ids) {
        if(ids == null || "".equals(ids)) {
            throw new CustomException(StatusCode.ID_IS_NULL);
        }
        String[] idArray = ids.split(",");

        int result = equipmentMapper.deleteOutdoorFitnessEquipmentByIds(idArray);
        if(result>0){
            String id = idArray[0];
            String outdoorFitnessId = equipmentMapper.selectByPrimaryKey(id).getOutdoorFitnessId();
            this.updateOutdoorFitnessById(outdoorFitnessId);
        }

        return result;
    }
}
